from sanic import Blueprint, response
from services import file_service

# 创建文件上传的Blueprint
s3_bp = Blueprint('s3', url_prefix='/s3')


# 文件上传API
@s3_bp.post('/upload_file')
async def upload_file(request):
    """文件上传接口"""
    # 检查是否有文件上传
    if 'file' not in request.files:
        return response.json({
            "code": 400,
            "message": "请选择要上传的文件"
        })
    
    # 获取文件数据
    file = request.files['file'][0]  # Sanic中，files返回的是字典，值是列表
    file_data = file.body
    filename = file.name
    
    # 调用服务层处理文件上传
    result = await file_service.upload_file(file_data, filename)
    
    return response.json(result)


# 文件删除API
@s3_bp.get('/delete_file/<filename>')
async def delete_file(request, filename):
    """删除文件接口"""
    # 调用服务层处理文件删除
    result = await file_service.delete_file_by_filename(filename)
    
    return response.json(result)